package fans_group

import (
	"context"
	"errors"
	global2 "longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/imsdk"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	room_event2 "longmen/server/internal/rpc/tencentim/room_event"
	"longmen/server/internal/services/nami/utils"
	"longmen/server/pkg/common/api_models"
	"longmen/server/pkg/common/helper/timehelper"
	"longmen/server/pkg/common/sdk/tx"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/db_live"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_live"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	"time"
)

func AddToGroup(fansGroupId string, userId int) (err error) {
	groupChat := cache.GetFansGroup(fansGroupId)
	if groupChat.Id <= 0 {
		err = errors.New("群组不存在")
		return
	}

	if groupChat.UserNum >= models_main.GroupChatLimitNum {
		err = errors.New("群人数已满")
		return
	}

	gcUser, err := db_main.GetGroupChatUser(map[string]interface{}{
		"user_id":  userId,
		"group_id": groupChat.Id,
	})
	if err != nil {
		return
	}
	if gcUser.Id > 0 {
		err = errors.New("用户已加入群组")
		return
	}

	return
}

type BanReq struct {
	AnchorId       int
	FansGroupId    string
	BanUserId      int
	OperateUserId  int
	DurationMinute int
	Reason         string
	BanType        int
	AdminId        int
}

var BanReasonMp = map[string]int{
	"广告营销诈骗": 1,
	"低俗色情":   2,
	"不实信息":   3,
	"不实消息":   3,
	"辱骂谩骂":   4,
	"违法有害信息": 5,
	"涉政言论":   6,
	"涉证言论":   6,
	"其他":     7,
	"发言触发风控": 9,
}

func SetGroupChatBan(req BanReq, fromEnd string) (err error) {
	banT := req.BanType
	mpT, ok := BanReasonMp[req.Reason]
	if ok {
		banT = mpT
	}

	banSecond := func() int64 {
		if req.DurationMinute >= 4294967295 { //永久禁言
			return 4294967295
		}
		return int64(req.DurationMinute * 60)
	}()

	defer DeleteHistoryAndImage(req)

	//设置直播间和群组禁言
	if fromEnd == "backend" {
		user, _ := mysql.GetUserParam(map[string]interface{}{
			"id": req.BanUserId,
		})
		banUser, _ := db_live.GetLiveRoomBanneduserParam(map[string]interface{}{
			"uid": req.BanUserId,
		})
		if banUser.Id <= 0 {
			err = db_live.InsertLiveRoomBanneduser(&models_live.LiveRoomBanneduser{
				Uid:        req.BanUserId,
				CreateTime: time.Now(),
				BanTime:    banSecond + time.Now().Unix(),
				Reason:     req.Reason,
				BanType:    req.BanType,
				BanMsg:     "",
				AdminId:    req.AdminId,
			})
			if err != nil {
				return err
			}
		} else {
			if banUser.BanTime > time.Now().Unix() {
				return errors.New("用户已经被禁言")
			}
			banUser.Anchorid = 0
			banUser.Mgrid = 0
			banUser.BanTime = banSecond + time.Now().Unix()
			banUser.Reason = req.Reason
			banUser.BanType = req.BanType
			banUser.AdminId = req.AdminId
			err = db_live.UpdateLiveRoomBanneduser(banUser, []string{"anchorid", "mgrid", "ban_time", "reason", "ban_Type", "admin_id"})
			if err != nil {
				return err
			}
		}
		return room_event2.BanUserAllChanSync(&messages2.BanUserChatReq{
			UserId:   req.BanUserId,
			BanType:  messages2.BanUserType,
			NickName: user.NickName,
			TBan:     banSecond,
			Reason:   req.Reason,
			BanMsg:   "",
		})
	}

	return room_event2.DoBanUser(&api_models.BanUserReq{
		Userid:   req.BanUserId,
		Type:     messages2.BanUserType,
		Anchorid: req.AnchorId,
		BanTime:  banSecond,         //用户被禁言的秒数
		Mgrid:    req.OperateUserId, // 操作人的id
		Reason:   req.Reason,
		BanType:  banT,
		BanMsg:   "",
	}, req.OperateUserId)
}

func SetGroupChatUnBan(req BanReq, fromEnd string) (err error) {
	//设置直播间和群组解禁
	if fromEnd == "backend" {
		user, _ := mysql.GetUserParam(map[string]interface{}{
			"id": req.BanUserId,
		})
		banUser, _ := db_live.GetLiveRoomBanneduserParam(map[string]interface{}{
			"uid": req.BanUserId,
		})
		if banUser.Id <= 0 {
			return errors.New("用户未被禁言")
		}
		res := global2.Live().Where("id=?", banUser.Id).Delete(&models_live.LiveRoomBanneduser{})
		if res.Error != nil {
			return res.Error
		}
		if res.RowsAffected > 0 {
			chatReq := &messages2.BanUserChatReq{
				UserId:   req.BanUserId,
				BanType:  messages2.UnbanUserType,
				NickName: user.NickName,
				TBan:     0,
				RoomId:   banUser.Anchorid,
				Reason:   "",
				BanMsg:   "",
			}
			if banUser.Anchorid > 0 {
				return room_event2.BanUserGroup(chatReq)
			}
			return room_event2.BanUserAllChanSync(chatReq)
		}
		return nil
	}
	//设置直播间和群组解禁
	return room_event2.DoBanUser(&api_models.BanUserReq{
		Userid:   req.BanUserId,
		Type:     messages2.UnbanUserType,
		Anchorid: req.AnchorId,
		BanTime:  int64(req.DurationMinute * 60), //用户被禁言的秒数
		Mgrid:    req.OperateUserId,              // 操作人的id
		Reason:   req.Reason,
		BanType:  0,
		BanMsg:   "",
	}, req.OperateUserId)
}

func SetGroupChatUserRole(userId, role int) error {
	if role == models_main.GroupChatRoleAdmin {
		manager, err := db_live.GetLiveRoomManagerParam(map[string]interface{}{
			"mgrid": userId,
		})
		if err != nil {
			global2.Log.Error(err)
		}
		if manager.Id <= 0 {
			err = db_live.InsertLiveRoomManager(&models_live.LiveRoomManager{
				Anchorid:   0,
				Mgrid:      userId,
				CreateTime: time.Now(),
			})
			if err != nil {
				return err
			}
		}

		gcUsers, err := db_main.GetGroupChatUserList(map[string]interface{}{
			"user_id": userId,
			"role":    models_main.GroupChatRoleMember,
		}, "", 0, 0)
		if err != nil {
			return err
		}
		if len(gcUsers) > 0 {
			ids := []int{}
			for _, v := range gcUsers {
				ids = append(ids, v.Id)
			}
			err = db_main.UpdateGroupChatUsersRoleAdmin(ids, models_main.GroupChatRoleAdmin)
			if err != nil {
				return err
			}
		}
	}
	if role == models_main.GroupChatRoleMember {
		manager, err := db_live.GetLiveRoomManagersParam(map[string]interface{}{
			"mgrid": userId,
		}, "", 0, 0)
		if err != nil {
			return err
		}

		ids := []int{}
		for _, v := range manager {
			ids = append(ids, v.Id)
		}
		if len(ids) > 0 {
			err = db_live.DeleteLiveRoomManager(map[string]interface{}{
				"mgrid": userId,
			})
			if err != nil {
				return err
			}
		}

		gcUsers, err := db_main.GetGroupChatUserList(map[string]interface{}{
			"user_id": userId,
			"role":    models_main.GroupChatRoleAdmin,
		}, "", 0, 0)
		if err != nil {
			return err
		}
		if len(gcUsers) > 0 {
			ids = []int{}
			for _, v := range gcUsers {
				ids = append(ids, v.Id)
			}
			err = db_main.UpdateGroupChatUsersRoleAdmin(ids, models_main.GroupChatRoleMember)
			if err != nil {
				return err
			}
		}
	}
	return nil
}

func CheckGroupUser(fansGroupId string, userId int) (code int, err error) {
	groupChat := cache.GetFansGroup(fansGroupId)
	if groupChat.Id <= 0 {
		code = imsdk.TIM_FANSG_REJECT_DISOLVE
		err = errors.New("群组已解散")
		return
	}

	//主播不允许发言
	if userId == groupChat.AnchorId {
		code = imsdk.TIM_FANSG_REJECT_FAILTIPS
		err = errors.New("发送失败")
		return
	}

	//检查用户是否禁言
	banUsers, _ := db_live.GetLiveRoomBanneduserParam(map[string]interface{}{
		"uid": userId,
		"anchorid": map[string]interface{}{
			"in": []int{0, groupChat.AnchorId},
		},
		"ban_time": map[string]interface{}{
			">": time.Now().Unix(),
		},
	})
	if banUsers.Id <= 0 {
		return 0, nil
	}
	sMsg := "被禁言" + timehelper.Time2Msg(banUsers.BanTime-time.Now().Unix())
	if len(banUsers.Reason) > 0 {
		sMsg = sMsg + ",原因:" + banUsers.Reason
	}
	return imsdk.TIM_FANSG_REJECT_BAN, errors.New(sMsg)
}

func DeleteHistoryAndImage(req BanReq) {
	//删除es信息
	defer func() {
		err := DeleteUserHistory(req.BanUserId, req.FansGroupId)
		if err != nil {
			global2.Log.Error(err)
		}
	}()
	//查出es图片消息, 删除bucket图片
	hs, err := SearchUserHistoryImage(req.BanUserId, req.FansGroupId)
	if err != nil {
		global2.Log.Error(err)
		return
	}
	for _, v := range hs {
		if len(v.ImageUrl) > 0 {
			tmp := v.ImageUrl
			utils.SafeGo(func() {
				err = tx.DeleteObject(tmp)
				if err != nil {
					global2.Log.Error(err)
				}
			})
		}
	}
}

func DeleteSingleHistory(h *FansGroupHistory, msgId string) (err error) {
	err = DelHistory(context.Background(), msgId)
	if err != nil {
		return
	}
	if len(h.ImageUrl) > 0 {
		err = tx.DeleteObject(h.ImageUrl)
	}
	return
}
